#!/usr/bin/python
import sys
import os
import tarfile
import shutil
import subprocess
import re

# set extra/contrib root
CONTRIB_SRC_DIR = os.getcwd()
CONTRIB_BINARY_DIR = os.getcwd()
CMAKE_BUILD_TYPE = "Release"
if len(sys.argv) > 1: CONTRIB_BINARY_DIR = sys.argv[1]
if len(sys.argv) > 2: CMAKE_BUILD_TYPE = sys.argv[2]

# build path is
BUILD_PREFIX = "%s/build-src" % CONTRIB_BINARY_DIR
INSTALL_PREFIX = "%s/build" % CONTRIB_BINARY_DIR

# prepare directories
def create_directory_if_not_exst( dir_path ):
		if not os.path.exists( dir_path ):
				os.makedirs( dir_path )
create_directory_if_not_exst( "%s/bin" % INSTALL_PREFIX )
create_directory_if_not_exst( "%s/lib" % INSTALL_PREFIX )
create_directory_if_not_exst( "%s/include" % INSTALL_PREFIX )
create_directory_if_not_exst( BUILD_PREFIX )

# for implement pushd/popd
directory_history = []

# utility functions
def pushd( d ):
	if not os.path.exists( d ): return 1
	directory_history.append( os.getcwd() )
	os.chdir( d )
	return 0

def popd():
	d = directory_history.pop()
	os.chdir( d )
	
def popd_and_exit():
	popd()
	exit( 1 )

def begin_build(PKG_NAME, PKG_VERSION):
	global CONTRIB_BINARY_DIR
	if os.path.exists( "%s/.build-%s-%s" % (CONTRIB_BINARY_DIR, PKG_NAME, PKG_VERSION) ):
		exit( 0 )

def end_build(PKG_NAME, PKG_VERSION):
	global CONTRIB_BINARY_DIR
	open( "%s/.build-%s-%s" % (CONTRIB_BINARY_DIR, PKG_NAME, PKG_VERSION), "w" ).close()

def do_extract(PKG_NAME, PKG_VERSION, PKG_ARCHIVE):
	global CONTRIB_BINARY_DIR
	global BUILD_PREFIX
	if not os.path.exists( "%s/.extract-%s-%s" % (CONTRIB_BINARY_DIR, PKG_NAME, PKG_VERSION) ):
		tar = tarfile.open("src/%s-%s.%s" % (PKG_NAME, PKG_VERSION, PKG_ARCHIVE))
		tar.extractall(BUILD_PREFIX)
		tar.close()
		open( "%s/.extract-%s-%s" % (CONTRIB_BINARY_DIR, PKG_NAME, PKG_VERSION), "w" ).close()

def do_patch(PKG_NAME, PKG_VERSION, POSTFIX=""):
	global CONTRIB_SRC_DIR
	global CONTRIB_BINARY_DIR
	global BUILD_PREFIX
	global CONTRIB_PATCH_UTILITY
	if os.path.exists( "%s/.patch-%s-%s%s" % (CONTRIB_BINARY_DIR, PKG_NAME, PKG_VERSION, POSTFIX) ): return()
	if not os.path.exists( "%s/src/patch/%s-%s%s" % (CONTRIB_SRC_DIR, PKG_NAME, PKG_VERSION, POSTFIX) ): return()
	pushd( "%s/%s-%s" % (BUILD_PREFIX, PKG_NAME, PKG_VERSION) )
	patch_path = "%s/src/patch/%s-%s%s" % (CONTRIB_SRC_DIR, PKG_NAME, PKG_VERSION, POSTFIX)
	dirList = os.listdir(patch_path)
	for name in dirList:
		if name.find(".svn") <> -1: continue
		if name.find(".patch") == -1: continue
		full_path = "%s/%s" % (patch_path, name)
		ret_value = os.system( "patch -p1 -i %s" % full_path )
		if ret_value != 0: popd_and_exit()
	popd()
	open( "%s/.patch-%s-%s%s" % (CONTRIB_BINARY_DIR, PKG_NAME, PKG_VERSION, POSTFIX), "w" ).close()

def recursive_copy(src, dst):
	if os.path.isdir(src):
		create_directory_if_not_exst( dst )
		dirList = os.listdir(src)
		for name in dirList:
			print( name );
			dst_filename = "%s/%s" % (dst, name)
			src_filename = "%s/%s" % (src, name)
			if os.path.isdir(src_filename):
				if os.path.exists(dst_filename): shutil.rmtree( dst_filename )
				shutil.copytree(src_filename, dst_filename)
			else:
				if os.path.exists(dst_filename): os.remove( dst_filename )
				shutil.copyfile(src_filename, dst_filename)
	else:
		if os.path.exists(dst): os.remove( dst )
		shutil.copyfile(src, dst)

def get_gcc_version():
	ver = ""
	p = subprocess.Popen(["gcc", "-v"], stderr=subprocess.PIPE)
	while True:
		line = p.stderr.readline()
		match = re.match("^gcc version ([\d.]+)", line)
		if match:
			ver = match.group(1)
			break

		elif line == '':
			break
	
	return ver

